import os

from app.globals import env
from app.macro import TradeAPIType
from app.mod_trade.api.tdx.tdx_api import TdxDllWorker
from app.mod_trade.model.mongo import Account
from libs.tdx.dll_api import load_dll

WORKER_CLS = {
    TradeAPIType.TDX: TdxDllWorker
}


def load_accounts():
    for account in Account.objects(enable=False):
        worker = env.workers.get(account.account)
        if worker:
            worker.stop()
            env.workers.pop(account.account)

    for account in Account.objects(enable=True):
        worker = env.workers.get(account.account)
        if not worker:
            worker_cls = WORKER_CLS[account.api_type]
            env.workers[account.account] = worker_cls(account=account)
            env.workers[account.account].start()


def init_mod_trade():
    dll_path = env.cfg.get("DLL_PATH")
    if not os.path.isfile(dll_path):
        dll_path = os.path.join(env.cfg_dir, dll_path)
    load_dll(dll_path)

    load_accounts()
